package ari.com.netty.server;

import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

/**
 * Handler implementation for the echo server.
 * 
 * @author <a href="http://www.jboss.org/netty/">The Netty Project</a>
 * @author <a href="http://gleamynode.net/">Trustin Lee</a>
 * 
 * @version $Rev: 2121 $, $Date: 2010-02-02 09:38:07 +0900 (Tue, 02 Feb 2010) $
 */
public class NettyEchoServerHandler extends SimpleChannelUpstreamHandler {

	private static final Logger logger = Logger
			.getLogger(NettyEchoServerHandler.class.getName());

	private final AtomicLong transferredBytes = new AtomicLong();

	public long getTransferredBytes() {
		return transferredBytes.get();
	}

	@Override
	public void messageReceived(final ChannelHandlerContext ctx,
			final MessageEvent e) {
		// Send back the received message to the remote peer.
		logger.log(Level.ALL, "Got the message:" + e.getMessage().toString());
		transferredBytes.addAndGet(((ChannelBuffer) e.getMessage())
				.readableBytes());
		e.getChannel().write("Returning :" + e.getMessage());
	}

	@Override
	public void exceptionCaught(final ChannelHandlerContext ctx,
			final ExceptionEvent e) {
		// Close the connection when an exception is raised.
		System.out.println("Exception caught :" + e.getCause());
		logger.log(Level.WARNING, "Unexpected exception from downstream.",
				e.getCause());
		e.getChannel().close();
	}
}
